package com.cd2cd.code_template.service.impl;

import com.cd2cd.code_template.code_template.domain.SysRelationUser;
import com.cd2cd.code_template.code_template.domain.SysUser;
import com.cd2cd.code_template.code_template.domain.gen.SysRelationUserCriteria;
import com.cd2cd.code_template.code_template.domain.gen.SysUserCriteria;
import com.cd2cd.code_template.code_template.mapper.SysRelationUserMapper;
import com.cd2cd.code_template.code_template.mapper.SysUserMapper;
import com.cd2cd.code_template.configuration.constants.ServiceCode;
import com.cd2cd.code_template.configuration.security.Md5PasswordEncoder;
import com.cd2cd.code_template.configuration.security.loginUserService.LoadUserService;
import com.cd2cd.code_template.service.SysUserService;
import com.cd2cd.code_template.util.BeanUtil;
import com.cd2cd.code_template.vo.BaseRes;
import com.cd2cd.code_template.vo.PageData;
import com.cd2cd.code_template.vo.SysUserVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;


@Component
public class SysUserServiceImpl implements SysUserService {


    @Resource
    private SysUserMapper sysUserMapper;


    @Resource
    private SysRelationUserMapper sysRelationUserMapper;

    @Override
    public BaseRes<PageData<SysUserVo>> getUserList(SysUserVo sysUserVo) {
        Integer current = sysUserVo.getCurrent() == null ? 1 : sysUserVo.getCurrent();
        Integer pageSize = sysUserVo.getPageSize() == null ? 10 : sysUserVo.getPageSize();

        BaseRes<PageData<SysUserVo>> res = new BaseRes<>(new PageData<>(current, pageSize), ServiceCode.SUCCESS);

        Integer mysqlLength = pageSize;
        Integer mysqlOffset = (current - 1) * mysqlLength;

        SysUserCriteria criteria = new SysUserCriteria();

        criteria.setMysqlLength(mysqlLength);
        criteria.setMysqlOffset(mysqlOffset);
        criteria.setOrderByClause(" id desc ");

        SysUserCriteria.Criteria criteriaCriteria = criteria.createCriteria();

        criteriaCriteria.andDelFlagEqualTo("ok");

        String nickname = sysUserVo.getNickname();

        if (StringUtils.isNotBlank(nickname)) {
            criteriaCriteria.andNicknameLike("%" + nickname + "%");
        }

        String status = sysUserVo.getStatus();

        if (StringUtils.isNotBlank(status)) {
            criteriaCriteria.andStatusEqualTo(status);
        }

        long count = sysUserMapper.countByExample(criteria);

        if (count > 0) {
            List<SysUser> sysUsers = sysUserMapper.selectByExample(criteria);
            List<SysUserVo> sysUserVos = BeanUtil.voConvertList(sysUsers, SysUserVo.class);
            res.getData().setRows(sysUserVos);
        }

        return res;
    }

    @Override
    public BaseRes<String> addUser(SysUserVo sysUserVo) {
        // 添加关联表

        SysUser sysUser = BeanUtil.voConvert(sysUserVo, SysUser.class);
        sysUser.setCreateTime(new Date());
        sysUser.setUpdateTime(new Date());
        sysUser.setDelFlag("ok");

        // 密码加密处理
        String password = Md5PasswordEncoder.md5Encode(sysUser.getPassword());
        sysUser.setPassword(password);

        sysUserMapper.insertSelective(sysUser);
        updateRelationUser(sysUser.getId(),sysUserVo.getRoles(),"role");
        updateRelationUser(sysUser.getId(),sysUserVo.getGroups(),"group");

        return new BaseRes<>(ServiceCode.SUCCESS);
    }

    /**
     * 处理角色关联
     */
    private void updateRelationUser(Integer userId,List<Integer> list,String type) {

        if (userId != null) {
            SysRelationUserCriteria criteria = new SysRelationUserCriteria();
            criteria.createCriteria().andUserIdEqualTo(userId).andTypeEqualTo(type);

            sysRelationUserMapper.deleteByExample(criteria);

            if (!CollectionUtils.isEmpty(list)) {
                for (Integer item : list) {
                    SysRelationUser record = new SysRelationUser();
                    record.setRelationId(item);
                    record.setUserId(userId);
                    record.setType(type);
                    record.setLoginType(LoadUserService.Backend.class.getSimpleName());
                    sysRelationUserMapper.insertSelective(record);
                }
            }
        }
    }

    @Override
    public BaseRes<String> updateUser(SysUserVo sysUserVo) {

        sysUserVo.setUpdateTime(new Date());

        // 更新权限
        updateRelationUser(sysUserVo.getId(),sysUserVo.getRoles(),"role");
        updateRelationUser(sysUserVo.getId(),sysUserVo.getGroups(),"group");
        sysUserMapper.updateByPrimaryKeySelective(sysUserVo);
        return new BaseRes<>(ServiceCode.SUCCESS);
    }

    @Override
    public BaseRes<String> delUser(SysUserVo sysUserVo) {
        sysUserVo.setUpdateTime(new Date());
        sysUserVo.setDelFlag("del");

        sysUserMapper.updateByPrimaryKeySelective(sysUserVo);
        return new BaseRes<>(ServiceCode.SUCCESS);
    }

    @Override
    public BaseRes<SysUserVo> userDetail(SysUserVo sysUserVo) {
        BaseRes<SysUserVo> res = new BaseRes<>(ServiceCode.SUCCESS);

        SysUser sysUser = sysUserMapper.selectByPrimaryKey(sysUserVo.getId());

        if (null != sysUser) {
            SysUserVo userVo = BeanUtil.voConvert(sysUser, SysUserVo.class);

            // 查询出所有关联角色
            List<Integer> roles = sysUserMapper.selectRelation(sysUser.getId(),"role");
            userVo.setRoles(roles);
            List<Integer> groups = sysUserMapper.selectRelation(sysUser.getId(), "group");
            userVo.setGroups(groups);

            res.setData(userVo);
        }

        return res;
    }
}
